#!/usr/bin/env python
# coding: utf-8

import ldap
import os
import MySQLdb
import ldap.modlist as modlist
from mod_mysql import *


LDAP_BIND = 'dc=sohutest,dc=com'

class ldap_open:

    def __init__(self):
        self.conn = ldap.initialize('ldap://10.16.48.124:389')
        self.conn.protocol_version = ldap.VERSION3
        self.conn.simple_bind('cn=admin,dc=sohutest,dc=com', 'sohutest')
        self.searchScope = ldap.SCOPE_SUBTREE
        self.mod_mysql = conn_mysql()

    def ldap_search(self,uid=None):
        searchFilter = "uid=*" + uid + "*"
        resultID = self.conn.search('dc=sohutest,dc=com', self.searchScope, searchFilter, None)
        result_set = []
        while 1:
            result_type, result_data = self.conn.result(resultID, 0)
            if (result_data == []):
                return "No such user..."
            else:
                if result_type == ldap.RES_SEARCH_ENTRY:
                    #result_set.append(result_data)
                    return result_data[0][0]

    def ldap_udate_pass(self,uid=None,oldpass=None,newpass=None):
        modify_entry = [(ldap.MOD_REPLACE,'userpassword',newpass)]
        targetDN = self.ldap_search(uid)
        try:
            #self.conn.simple_bind_s(target,oldpass)
            self.conn.passwd(targetDN,oldpass,newpass)
            self.mod_mysql.update_pass(uid,newpass)
            return 'ok'
        except ldap.LDAPError,e:
            return e,'False'

    def ldap_user_del(self,uid=None):
        try:
            deleteDN = self.ldap_search(uid)
            self.conn.delete(deleteDN)
            self.mod_mysql.del_user(uid)
            #os.system('rm -fr /home/user/%s' %uid)
            return 'ok'
        except ldap.LDAPError, e:
            return e

    def ldap_group_add(self,gid=None):
        try:
            addDN = "cn=%s,ou=People,dc=sohutest,dc=com" % gid
            g = int(self.mod_mysql.s_gid())+1
            attrs = {}
            attrs['objectClass'] = ['posixGroup']
            attrs['cn'] = [uid]
            attrs['gidNumber'] = ['%s' %g]
            self.conn.add_s(addDN, modlist.addModlist(attrs))
            self.conn.unbind_s()
            return 'ok'
        except ldap.LDAPError,e:
            return e

    def ldap_user_add(self,uid=None,dt=None):
        try:
            addDN = "cn=%s,ou=People,dc=sohutest,dc=com" % uid
            u = int(self.mod_mysql.s_uid())+1
            g = int(self.mod_mysql.s_gid(dept=dt))
            p = self.mod_mysql.r_pas()
            m = uid + '@sohu-inc.com'
            attrs = {}
            attrs['cn'] = [uid]
            attrs['ou'] = ['People']
            #attrs['homeDirectory'] = ['/home/user/%s' % uid]
            attrs['homeDirectory'] = ['/home/user/ldapuser']
            attrs['loginShell'] = ['/bin/bash']
            attrs['uid'] = [uid]
            attrs['uidNumber'] = ['%s' %u]
            attrs['gidNumber'] = ['%s' %g]
            attrs['userPassword'] = p
            attrs['objectClass'] =  ['account', 'posixAccount', 'top', 'shadowAccount']
            self.conn.add_s(addDN, modlist.addModlist(attrs))
            #self.conn.unbind_s()
            #os.system("mkdir /home/user/%s" %uid)
            self.mod_mysql.add_user(uid,p,u,g,dt,m)
            return 'ok',p
        except ldap.LDAPError,e:
            return e

    def ldap_user_mod(self,uid=None):
        try:
            modDN = "cn=%s,ou=People,dc=sohutest,dc=com" % uid
            g = self.mod_mysql.s_gid(user=uid)
            old = {'gidNumber':g}
            new = {'gidNumber':'10000'}
            ldif = modlist.modifyModlist(old, new)
            self.conn.modify_s(modDN,ldif)
            self.conn.unbind_s()
            return 'ok'
        except ldap.LDAPError,e:
            return e

if __name__ == '__main__':
    l = ldap_open()
    a = aes_crypto()
    #print l.ldap_udate_pass('jiayusun','sis%(l','sis%(l#!')
    print l.ldap_user_add('zhangjun','API')
